package net.hancl.modules.sys.shiro;

import net.hancl.common.cache.EhCacheKeys;
import net.hancl.modules.sys.constants.SysComm;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

import java.util.concurrent.atomic.AtomicInteger;

public class CredentialsMatcher extends HashedCredentialsMatcher {

    private Cache<String, AtomicInteger> userLonginLogCache;

    public CredentialsMatcher(CacheManager cacheManager) {
        userLonginLogCache = cacheManager
                .getCache(EhCacheKeys.LONGIN_COUNT);
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {

        String username = (String)token.getPrincipal();

        AtomicInteger loginCount = userLonginLogCache.get(username);
        if(loginCount == null){
            loginCount = new AtomicInteger(0);
            userLonginLogCache.put(username, loginCount);
        }

        if(loginCount.incrementAndGet() >= SysComm.USER_LOGIN_MAX_COUNT_LOCK){
            throw new ExcessiveAttemptsException();
        }

        // importance 关键点
        boolean matches = super.doCredentialsMatch(token, info);
        if (matches) {
            userLonginLogCache.remove(username);
        }
        return matches;
    }
}
